/*
1.树的同构 小白专场会做详细讲解，基本要求，一定要做
*/

#include <stdio.h>
#include <stdlib.h>
#define maxsize 10

struct Tree {
    char data;
    int left;
    int right;
}T1[maxsize], T2[maxsize]; 

int buildTree(struct Tree T[]) {
    int N;
    char l, r;
    scanf("%d\n", &N);
    int check[N];
    for (int i=0; i < N; ++i) {check[i] = 0;}
    for (int i = 0; i < N; ++i) {
        scanf("%c %c %c\n", &T[i].data, &l, &r);
        if (l != '-') {
            T[i].left = l - '0';
            check[T[i].left] = 1;
        } else T[i].left = -1;
        if (r != '-') {
            T[i].right = r - '0';
            check[T[i].right] = 1;
        } else T[i].right = -1;
    }
    int root = -1;
    for (int i=0; i < N;++i) {
        if (!check[i]) {
            root = i;
            break;
        }
    }
    return root;
}

int isSame(int R1, int R2) {
    if (R1 == -1 && R2 == -1) return 1;
    if (T1[R1].data != T2[R2].data) return 0;
    if((R1==-1 && R2 !=-1) || (R1!=-1 && R2 ==-1)) return 0;
    if ((T1[R1].left==-1) && (T2[R2].left==-1)) {
        return isSame(T1[R1].right, T2[R2].right);
    }
    if ((T1[R1].right==-1) && (T2[R2].right==-1)) {
        return isSame(T1[R1].left, T2[R2].left);
    }
    if (((T1[R1].left!=-1) && (T2[R2].left!=-1)) &&
       (T1[T1[R1].left].data == T2[T2[R2].left].data)) {
        return (isSame(T1[R1].left, T2[R2].left) && 
                isSame(T1[R1].right, T2[R2].right));
    } else {
        return (isSame(T1[R1].left, T2[R2].right) && 
                isSame(T1[R1].right, T2[R2].left));
    }
}
int main(int argc, char* argv[]) {
    int root1, root2;
    root1 = buildTree(T1);
    root2 = buildTree(T2);
    int answer = isSame(root1, root2);
    if (answer) printf("Yes\n");
    else printf("No\n");
    return 0;
}